package com.rabiitmq.spring;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ListenerAck {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "spring.test.queue", durable = "true"),
            exchange = @Exchange(
                    value = "spring.test.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"#.#"}))
    public void message(Message message, Channel channel) throws  Exception{
        //接受消息
        System.out.println(message.getBody());
        try {
            System.out.println("业务处理");
            // 没有出现异常，手动确认该消息，消息队列会删除该消息
            channel.basicAck(
                    /// 获取消息的传送标签，queue使用该标签进行确认消息
                    message.getMessageProperties().getDeliveryTag(),
                    false // 是否把之前的消息全都确认。
            );
        }catch (Exception e){
            // 如果出现异常，不确认该消息
            channel.basicNack(
                    message.getMessageProperties().getDeliveryTag(),
                    false, // 是否确认多条
                    false // 是否重新发送
            );
        }
    }
}
